import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
import Dialog from "../../miniprogram_npm/@vant/weapp/dialog/dialog";
import Big from "../../utils/big.min";
import storage from './storage';
import {
  ajaxGetOrderingList,
  ajaxGetHotProductList,
  ajaxGetStoreList
} from "../../api/ordering";
import {
  ajaxGetBannerList
} from '../../api/home'

const app = getApp();
// 防止重复调用弹框
let isShowModal = false;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //自定义导航信息
    customNavInfo: app.globalData.customNavInfo,
    baseURL: app.globalData.config.baseURL,
    // 列表数据
    list: [],
    // 左侧导航
    leftOptions: {
      // 选中分类
      activeIndex: 0,
      // 锚点
      leftToView: ""
    },
    // 右侧商品
    rightOptions: {
      // 锚点
      rightToView: "",
      //右侧滚动距离
      rightScrollTop: 0,
    },
    //购物车数据
    shoppingCartData: {
      show: false,
      list: [],
      totalMoney: 0,
      totalNum: 1,
    },
    // 右侧滚动定时器
    scrollTime: null,
    //是否跳转任务中
    isJumpTask: false,
    //容器高度
    containerH: 0,
    //左侧内容高度
    leftHeightArr: [],
    //右侧内容高度
    rightHeightArr: [],
    //记录scroll-view滚动过程中距离顶部的高度
    rightDistance: 0,
    leftDistance: 0,
    // 广告
    isShowAdvertisement: false,
    advertisementUrl: '',
    // 通知消息
    noticeText: '年度会员才有参加比赛权限（部分套餐已包含年度会员）',
    // 店铺信息
    shopInfo: null,
    // 是否显示手动选择店铺布局
    isShowSelectShop: false,
    // 被删除的商品
    deleteProductList: []
  },
  // 本地存储方法
  ...storage.methods,
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  // 刷新页面
  refreshData() {
    //loading
    Toast.loading({
      message: '正在加载',
      forbidClick: true,
      duration: 0
    });
    this.getListData();
    // 关闭广告的日期
    let closeAdvertisementDate = wx.getStorageSync('closeAdvertisementDate'),
      // 今天日期
      currentDate = app.dateFormat(Date.now());
    // 没有关闭日期 || 当前日期小于关闭广告的日期则显示广告
    if (!closeAdvertisementDate || currentDate.localeCompare(closeAdvertisementDate) > 0) {
      this.getAdvertisement();
    }
  },
  // 清空被删除商品
  clearDeleteProduct() {
    this.setData({
      deleteProductList: []
    })
  },
  // 前往选择门店页面
  toSelectProduct() {
    app.commonNavigateTo(`/pages/ordering/selectStore/index`)
  },
  // 获取广告图数据
  async getAdvertisement() {
    try {
      let {
        data
      } = await ajaxGetBannerList({
        dictionaryType: 5
      });
      if (data && data.length) {
        this.setData({
          advertisementUrl: data[0].dictionaryDesc,
          isShowAdvertisement: true
        })
      }
    } catch (err) {

    }
  },
  // 关闭广告
  closeAdvertisement() {
    //存储关闭时间
    wx.setStorageSync('closeAdvertisementDate', app.dateFormat(Date.now()));
    this.setData({
      isShowAdvertisement: false
    })
  },
  // 获取列表数据数据
  async getListData() {
    let [{
      'data': ordinaryList
    }, {
      'data': hotList
    }] = await Promise.all([
        ajaxGetOrderingList({
          "filterPrice": "Y",
          "productStatus": 0
        }),
        ajaxGetHotProductList()
      ]),
      // 分类
      classifyObj = {},
      // 调整热门商品字段名，分类数据
      list = [];
    [...(ordinaryList || []), ...(hotList || [])].forEach(item => {
      // 组成产品结构
      let newItem = this.getProductDataStructure(item);
      if (!classifyObj[newItem.classifyId]) {
        classifyObj[newItem.classifyId] = [];
      }
      classifyObj[newItem.classifyId].push(newItem);
    });

    // 分组
    for (const key in classifyObj) {
      let arr = JSON.parse(JSON.stringify(classifyObj[key]));
      let group = {
        classifyId: arr[0].classifyId,
        classifyName: arr[0].classifyName,
        productInfoVoList: arr
      }
      // 热门套餐排最前面
      if (key == -1) {
        list.unshift(group);
      } else {
        list.push(group);
      }
    }
    classifyObj = {};

    //获取本店铺本地购物车数据
    let shoppingList = this.getShoppingCartStorage(),
      // 新购物车数据
      newShoppingList = [],
      // 被删除的商品
      deleteProductList = [];
    // 比对本地购物车数据是否有商品删除
    shoppingList.forEach(shoppingItem => {
      let isExist = list.find(classifyItem => {
        return classifyItem.productInfoVoList.find(productItem => {
          let isId = this.compareId(shoppingItem, productItem);
          // 匹配成功修改商品数量
          if (isId) {
            productItem.num = shoppingItem.num || 0
          }
          return isId
        })
      })
      // 存在
      if (isExist) {
        newShoppingList.push(JSON.parse(JSON.stringify(shoppingItem)));
      } else {
        // 被删除
        deleteProductList.push(JSON.parse(JSON.stringify(shoppingItem)));
      }
    })

    //购物车商品总价格和总数计算
    let {
      totalMoney,
      totalNum
    } = this.getCalcData(newShoppingList);

    //同步本地存储
    this.updateShoppingCartStorage(newShoppingList);

    this.setData({
      list: list,
      deleteProductList,
      'shoppingCartData': {
        list: newShoppingList,
        totalMoney,
        totalNum
      }
    }, async () => {
      //计算右侧每一个分类的高度
      this.selectHeight();
      await app.myNextTick()
      Toast.clear();
    });
  },
  // 组成产品结构
  getProductDataStructure(item) {
    return {
      productName: item.productName || item.packageName,
      productImage: item.productImage || item.packageImage,
      // 商品id
      productId: item.productId,
      // 产品金额
      productPrice: item.productPrice || item.sumAmount || 0,
      // 套餐id
      packageId: item.packageId,
      // 分类id
      classifyId: item.categoryId || -1,
      // 分类名称
      classifyName: item.categoryName || '热门套餐',
      // 产品默认数量
      num: 0
    }
  },
  //计算右侧每一个分类的高度
  selectHeight() {
    let that = this;
    this.rightHeightArr = [];
    this.leftHeightArr = [];
    let rightH = 0,
      leftH = 0;
    const query = wx.createSelectorQuery();
    query.selectAll('#right-scroll >>> .classify-group').boundingClientRect()
    query.selectAll('#left-scroll >>> .classify-item').boundingClientRect()
    query.select('#right-scroll >>> .commodityClassify-wrap').boundingClientRect()
    query.exec(function (res) {
      let [rightGroup, leftGroup, container] = res;
      //容器高度
      that.containerH = container.height;
      rightGroup.forEach((item) => {
        rightH += item.height;
        that.rightHeightArr.push(rightH);
      })
      leftGroup.forEach((item) => {
        leftH += item.height;
        that.leftHeightArr.push(leftH);
      })
    })
  },
  //分类跳转
  jump(e) {
    let {
      index
    } = e.detail;
    this.rightDistance = this.rightHeightArr[index];
    this.isJumpTask = true;
    this.setData({
      "leftOptions.activeIndex": index,
      'rightOptions.rightScrollTop': index == 0 ? 0 : this.rightHeightArr[index - 1]
    });
  },
  //右侧列表滚动监听
  rightScroll(e) {
    if (this.scrollTime) {
      clearTimeout(this.scrollTime)
      this.scrollTime = null;
    }
    if (this.isJumpTask) {
      this.scrollTime = setTimeout(() => {
        this.isJumpTask = false;
        this.rightDistance = 0;
        //左侧跳转滚动结束，在执行一次右侧定位
        let index = this.data.leftOptions.activeIndex;
        this.setData({
          'rightOptions.rightScrollTop': index == 0 ? 0 : this.rightHeightArr[index - 1]
        });
      }, 100)
      return;
    }
    this.scrollTime = setTimeout(() => {
      this.delayRightSscroll(e.detail || {});
    }, 100)
  },
  //左侧列表滚动监听
  leftScroll(e) {
    if (this.leftHeightArr.length == 0) {
      return;
    }
    //更新到顶部的距离
    this.leftDistance = e.detail;
  },
  //延迟右侧列表滚动处理
  delayRightSscroll(e) {
    if (this.rightHeightArr.length == 0) {
      return;
    }
    let {
      scrollTop,
      scrollHeight
    } = e.detail;
    let current = this.data.leftOptions.activeIndex;
    //左侧点击分类会触发滚动，禁止跳动
    if (this.rightDistance != 0 && (this.rightDistance > scrollTop || scrollTop > scrollHeight - this.containerH)) {
      // console.log(this.rightDistance, scrollTop, scrollHeight - this.containerH);
      // console.log('左侧点击分类会触发滚动，禁止跳动');
      this.rightDistance = 0;
      return;
    }
    for (let i = 0; i < this.rightHeightArr.length; i++) {
      const itemH = this.rightHeightArr[i];
      //匹配分组index
      if (itemH > scrollTop) {
        if (i != current) {
          this.setData({
            'leftOptions.activeIndex': i
          })
        }
        //判断左侧选中项是否在展示区域 没有则跳转
        let prevH = this.leftHeightArr[i - 1] || 0;
        if (prevH <= this.leftDistance) {
          // console.log('左侧跳转');
          this.setData({
            'leftOptions.leftToView': `leftToView${i}`
          })
        }
        break;
      }
    }
    this.rightDistance = 0;
  },
  //控制购物车弹层
  setLayerShow(e) {
    this.setData({
      "shoppingCartData.show": e.detail || false,
    });
  },
  // 清空购物车
  clearShoppingCart() {
    Dialog.confirm({
        message: `确定清空购物车吗?`,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonColor: "#e61211",
        zIndex: 120,
      })
      .then(() => {
        //清空购物车数据
        this.clearShoppingCartHandle();
        //删除此商铺本地购物车数据
        this.deleteShoppingCartStorage();
      })
      .catch(() => {});
  },
  // 清空购物车处理方法
  clearShoppingCartHandle() {
    //记录需要更新的同商品
    let updateLog = {};
    this.data.list.forEach((classifyItem, classifyIndex) => {
      classifyItem.productInfoVoList.forEach((productItem, productIndex) => {
        if (productItem.num) {
          updateLog[
            `list[${classifyIndex}].productInfoVoList[${productIndex}]`
          ] = Object.assign({}, productItem, {
            num: 0,
          });
        }
      });
    });
    this.setData({
      shoppingCartData: {
        show: false,
        list: [],
        totalMoney: 0,
        totalNum: 0,
      },
      ...updateLog,
    });
  },
  // 通过购物车更新商品
  shoppingCartUpdateCommodity(e) {
    let {
      productId,
      packageId,
      index,
      type,
      clear
    } = e.detail,
      list = this.data.shoppingCartData.list,
      item = JSON.parse(JSON.stringify(list[index]));
    //清除商品
    if (clear) {
      this.setData({
        [`list[${index}].num`]: 0
      })
      this.updateData(type, item);
      // this.isDeleteCommodity();
    } else {
      this.updateBefore(type, item);
    }
  },
  // 通过列表更新商品
  updateCommodity(e) {
    let {
      groupIndex,
      index,
      type
    } = e.detail, {
        list
      } = this.data.shoppingCartData,
      item = JSON.parse(JSON.stringify(this.data.list[groupIndex].productInfoVoList[index]));
    this.updateBefore(type, item);
  },
  //更新之前计算加减值
  updateBefore(type, item) {
    let currentNum = item.num || 0,
      //当前购物车同商品总数
      currentTotalNum = this.getCommodityNum(item.productId, item.packageId) - currentNum;
    //数量修改
    if (type == "add") {
      currentNum += 1;
    } else if (type == "reduce") {
      currentNum -= 1;
    }
    currentNum = currentNum < 0 ? 0 : currentNum;
    item.num = currentNum;
    //更新购物车和分类商品列表数据
    this.updateData(type, item);
  },
  // 获取商品在购物车的总数
  getCommodityNum(productId, packageId, list) {
    let totalNum = 0;
    if (!list) {
      list = this.data.shoppingCartData.list;
    }
    list.forEach((item) => {
      if (this.compareId({
          productId,
          packageId
        }, item)) {
        totalNum += item.num;
      }
    });
    return totalNum;
  },
  // 更新从详情页面添加的商品
  updateDetailsPageProduct(productObj) {
    //查找商品
    for (let i = 0; i < this.data.list.length; i++) {
      let productInfoVoList = this.data.list[i].productInfoVoList;
      for (let j = 0; j < productInfoVoList.length; j++) {
        let productItem = productInfoVoList[j];
        if (this.compareId(productItem, productObj)) {
          this.updateData('add', JSON.parse(JSON.stringify(Object.assign({}, productItem, {
            num: productItem.num + productObj.num
          }))));
          return;
        }
      }
    }
  },
  /**
   * 传入更新商品信息，更新购物车和分类商品列表数据
   * @param {*} type 操作类型
   * @param {*} productObj 商品对象
   */
  updateData(type, productObj) {
    //商品对象
    productObj = Object.assign({}, productObj, {
      totalMoney: parseFloat(Big.add(totalMoney || 0, Big.multiply(productObj.productPrice, productObj.num))).toFixed(2)
    });
    let {
      list
    } = this.data.shoppingCartData,
      //记录更新
      updateLog = {},
      //购物车相同商品索引
      identicalIndex = list.findIndex(item => {
        //id是否相同
        let isId = this.compareId(productObj, item);
        return isId;
      });

    //购物车存在相同商品
    if (identicalIndex != -1) {
      // 覆盖数量对象
      Object.assign(list[identicalIndex], list[identicalIndex], {
        num: productObj.num,
        totalMoney: parseFloat(Big.multiply(productObj.productPrice, productObj.num)).toFixed(2)
      });
      if (type == 'add') {
        updateLog[`shoppingCartData.list[${identicalIndex}]`] = list[identicalIndex]
      } else if (type == 'reduce') {
        //数量为0 删除此商品
        if (productObj.num <= 0) {
          list.splice(identicalIndex, 1)
          updateLog[`shoppingCartData.list`] = list;
          //购物车无商品隐藏弹层
          if (!list.length) {
            updateLog[`shoppingCartData.show`] = false
          }
        } else {
          updateLog[`shoppingCartData.list[${identicalIndex}]`] = list[identicalIndex]
        }
      }
    } else {
      //购物车不存在相同商品
      if (type == 'add') {
        list.push(Object.assign({}, productObj, {
          totalMoney: parseFloat(Big.multiply(productObj.productPrice, productObj.num)).toFixed(2)
        }));
        updateLog[`shoppingCartData.list`] = list;
      }
    }

    //购物车商品总价格和总数计算
    let {
      totalMoney,
      totalNum
    } = this.getCalcData(list);
    updateLog[`shoppingCartData.totalMoney`] = parseFloat(totalMoney).toFixed(2);
    updateLog[`shoppingCartData.totalNum`] = totalNum;

    //计算此商品在购物车的总数量
    let productNum = 0;
    list.forEach(item => {
      if (this.compareId(productObj, item)) {
        productNum += item.num;
      }
    })

    //记录更新 更新分类数据里的相同商品的数量
    this.data.list.forEach((classifyItem, classifyIndex) => {
      classifyItem.productInfoVoList.forEach((productItem, productIndex) => {
        if (this.compareId(productItem, productObj)) {
          updateLog[`list[${classifyIndex}].productInfoVoList[${productIndex}]`] = JSON.parse(JSON.stringify(Object.assign({}, productItem, {
            num: productNum
          })))
        }
      });
    });

    //渲染
    this.setData({
      ...updateLog
    })
    //同步本地存储
    this.updateShoppingCartStorage(list);

  },
  // 比较商品id或套餐id
  compareId(oneItem, twoItem) {
    return (oneItem.productId && twoItem.productId == oneItem.productId) || (oneItem.packageId && twoItem.packageId == oneItem.packageId)
  },
  //获取计算总金额和总数量
  getCalcData(list) {
    //计算总金额和总数量
    let totalMoney = 0,
      totalNum = 0;
    for (let i = 0; i < list.length; i++) {
      let commodityItem = list[i];
      totalMoney = parseFloat(Big.add(totalMoney, Big.multiply(commodityItem.productPrice, commodityItem.num))).toFixed(2);
      totalNum = Big.add(totalNum, commodityItem.num);
    }
    return {
      totalMoney,
      totalNum
    }
  },
  //去商品详情页面
  goProductDetails(e) {
    let {
      groupIndex,
      index,
      // 数量
      num,
      // 从购物车里点击会直接传递id
      productId,
      packageId,
    } = e.detail;
    // 从列表点击没有id
    if (!productId && !packageId) {
      let item = this.data.list[groupIndex].productInfoVoList[index];
      if (item.packageId) {
        packageId = item.packageId;
      } else {
        productId = item.productId;
      }
      num = item.num
    }
    app.commonNavigateTo(`/pages/ordering/productDetails/index?id=${packageId||productId}&type=${packageId?2:1}&num=${num||0}`)
  },
  // 去下单
  toPlaceOrder() {
    if (!this.data.shoppingCartData.list.length) {
      Toast('购物车没有商品')
      return;
    }
    if (app.globalData.userInfo) {
      app.commonNavigateTo('/pages/ordering/orderPayment/index', JSON.parse(JSON.stringify(this.data.shoppingCartData)))
    } else {
      app.commonNavigateTo('/pages/registerLogin/home/index')
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {

    // 已经弹出的提示框
    if (isShowModal) {
      return;
    }

    // 没有店铺信息
    if (!app.globalData.shopInfo) {
      //loading
      Toast.loading({
        message: '正在获取位置',
        forbidClick: true,
        duration: 0
      });
      this.setData({
        isShowSelectShop: false
      })
    }

    // 店铺信息改变
    if (JSON.stringify(this.data.shopInfo) != JSON.stringify(app.globalData.shopInfo)) {
      this.setData({
        shopInfo: app.globalData.shopInfo,
        leftDistance: 0,
        rightDistance: 0,
        leftOptions: {
          activeIndex: 0,
          leftToView: ''
        },
        rightOptions: {
          rightScrollTop: 0,
          rightToView: ''
        }
      })
      // 刷新数据
      if (app.globalData.shopInfo) {
        this.refreshData();
      }
    }

    // 没有店铺信息，获取地理位置
    if (!app.globalData.shopInfo) {
      try {
        let locationData = await app.getLocation();
        if (locationData) {
          // 得到地理位置数据
          let {
            data
          } = await ajaxGetStoreList({
            longitude: locationData.longitude,
            latitude: locationData.latitude,
            limit: 1,
            ifCommonUse: 'N'
          })
          let shopList = data.shopList || [];
          if (shopList.length) {
            this.setData({
              shopInfo: JSON.parse(JSON.stringify(shopList[0])),
              isShowSelectShop: false
            })
            app.globalData.shopInfo = JSON.parse(JSON.stringify(shopList[0]))
            // 刷新数据
            this.refreshData();
          } else {
            // 显示手动选择店铺布局
            this.setData({
              isShowSelectShop: true
            })
            await app.myNextTick()
            Toast.clear();
            Toast('没有店铺')
          }
        } else {
          // 显示手动选择店铺布局
          this.setData({
            isShowSelectShop: true
          })
          await app.myNextTick()
          Toast.clear();
          isShowModal = true;
          // 没有获取到地理位置
          wx.showModal({
            title: '地理位置获取失败',
            content: '获取地理位置失败，请手动选择店铺',
            confirmColor: '#e61211',
            success: (res) => {
              isShowModal = false;
              if (res.confirm) {
                // 前往选择店铺
                this.toSelectProduct()
              } else if (res.cancel) {
                // console.log('用户点击取消')
              }
            }
          })
        }
      } catch (err) {
        await app.myNextTick()
        Toast.clear();
        Toast(err.msg || '错误')
      }
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},
});